package 笔试.拼多多;

import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Scanner;

public class Demo1 {
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        int T = in.nextInt();
        int[] ans = new int[T];
        for(int i=0;i<T;i++){
            int N = in.nextInt();
            Queue<int[]> queue = new PriorityQueue<>(new Comparator<int[]>(){
                @Override
                public int compare(int[] o1,int[] o2){
                    if(o1[1]==o2[1]){
                        return o2[0]-o1[0];
                    }
                    return o2[1]-o1[1];
                }
            });

            for(int j=0;j<N;j++){
                int s = in.nextInt();
                int t = in.nextInt();
                queue.add(new int[]{s,t});
            }
            int[] temp =  queue.poll();
            int count = temp[1];
            int sum = temp[0];
            while(!queue.isEmpty()){
                if(count==0) break;
                temp = queue.poll();
                count = Math.min(count-1,temp[1]);
                if(count>0){
                    sum += temp[0];
                }
            }
            ans[i] = sum;
        }
        for (int t : ans) {
            System.out.println(t);
        }


    }

}
